package com.pad.filelibrary.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

public class PermissionUtils {
    /**
     * 检查并请求权限
     * @param activity 当前的 Activity
     * @param permissions 需要检查和请求的权限数组
     * @param requestCode 请求权限的请求码
     * @return 如果所有权限都已经授予，返回 true；否则返回 false
     */
    public static boolean checkAndRequestPermissions(Context activity, String[] permissions, int requestCode) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        List<String> permissionsToRequest = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(permission);
            }
        }

        if (!permissionsToRequest.isEmpty()) {
//            ActivityCompat.requestPermissions(activity, permissionsToRequest.toArray(new String[0]), requestCode);
            return false;
        }
        return true;
    }

    /**
     * 检查权限请求结果
     * @param grantResults 权限请求结果数组
     * @return 如果所有权限都被授予，返回 true；否则返回 false
     */
    public static boolean verifyPermissions(int[] grantResults) {
        if (grantResults.length < 1) {
            return false;
        }
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查是否应该显示权限请求的解释说明
     * @param activity 当前的 Activity
     * @param permissions 需要检查的权限数组
     * @return 如果有任何一个权限需要显示解释说明，返回 true；否则返回 false
     */
    public static boolean shouldShowRequestPermissionRationale(Activity activity, String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return false;
        }
        for (String permission : permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
                return true;
            }
        }
        return false;
    }
}
